package consistenthash

import (
	"crypto/md5"
	"log"
	"os"
)


type Selector struct {
	virStoreNode *TreeMap
	repNum       int
	logger       *log.Logger
}
func NewSelector() *Selector {
	selector := &Selector{
		virStoreNode: NewTreeMap(),
		repNum:       4,
		logger:       log.New(os.Stderr, "[selector] ", log.LstdFlags),
	}

	return selector
}
func(s *Selector) Add(key string,value string){

}

func(s *Selector) Select(invocation string)string{
	key := s.toKey(invocation)
	digest := s.md5(key)
	return s.selectForKey(s.hash(digest,0))
}

func (s *Selector) selectForKey(hash int64) string {
	entry := s.virStoreNode.GetCeilingEntry(hash)
	if entry ==nil{
		entry = s.virStoreNode.FirstEntry()
	}
	return entry.value.(string)
}
func (s *Selector) hash(digest []byte, number int) int64 {
	a1 := int64(digest[3 + number * 4] & 0xFF) << 24
	a2:=int64(digest[2 + number * 4] & 0xFF) << 16
	a3 := int64(digest[1 + number * 4] & 0xFF) << 8
	a4 := int64(digest[number * 4] & 0xFF)
	a5 := int64(a1 | a2 | a3 | a4) &0xFFFFFFFF
	return a5
}

func (s *Selector) md5(key string) []byte {
	hash := md5.New()
	sum := hash.Sum([]byte(key))
	return sum
}

func (s *Selector) toKey(key string) string {
	return key
}